package com.treetao.union.web.controller.pitch;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.treetao.union.core.amap.geocode.geo.GeocodeApi;
import com.treetao.union.core.amap.geocode.geo.GeocodeResp;
import com.treetao.union.core.amap.geocode.geo.Geocodes;
import com.treetao.union.db.model.PitchAddr;
import com.treetao.union.db.service.PitchAddrService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.treetao.union.db.model.vo.LayerData;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.web.constant.Constants;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletRequest;
import java.util.Map;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 摊位地址  前端控制器
 * </p>
 *
 * @author Dev.M
 * @since 2020-06-07
 */
@Controller
@RequestMapping(Constants.AMIND_PREFIX + "/pitch-addr")
public class PitchAddrController {

    @Autowired
    private PitchAddrService pitchAddrService;

    @GetMapping("list")
    public String list(){
        return "/admin/pitch-addr/list";
    }
    
    String amapKey = "自行申请高德地图appKey";//输入地址时，反查出经纬度

    @PostMapping("list")
    @ResponseBody
    public LayerData<PitchAddr> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                      @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                      ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        LayerData<PitchAddr> layerData = new LayerData<>();
        QueryWrapper<PitchAddr> wrapper = new QueryWrapper<PitchAddr>();
        if(!map.isEmpty()){
        	String delFlag = (String) map.get("delFlag");
            if(StringUtils.isNotBlank(delFlag)) {
                wrapper.eq("del_flag",Boolean.valueOf(delFlag));
            }else{
                map.remove("del_flag");
            }
        }
        IPage<PitchAddr> pageData = pitchAddrService.page(new Page<>(page,limit),wrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    @GetMapping("add")
    public String add(){
        return "/admin/pitch-addr/add";
    }

    @PostMapping("add")
    @ResponseBody
    public RestResponse add(PitchAddr pa){
    	if(StringUtils.isEmpty(pa.getPitchAddress())) {
    		 return RestResponse.failure("地址必须输入");
    	}
    	//填充地理编码结果信息 
    	GeocodeResp resp = GeocodeApi.getGeocode(amapKey, pa.getPitchAddress());
    	convert(resp, pa);
    	pitchAddrService.save(pa);
    	
        return RestResponse.success();
    }
    
    private void convert(GeocodeResp resp,PitchAddr pa) {
    	if(resp!=null && resp.getGeocodes()!=null && resp.getGeocodes().size()>0) {
    		Geocodes geo = resp.getGeocodes().get(0);
    		pa.setAdcode(geo.getAdcode());
    		pa.setCity(geo.getCity());
    		pa.setCitycode(geo.getCitycode());
    		pa.setDistrict(geo.getDistrict());
    		pa.setNumber(geo.getNumber()==null || geo.getNumber() instanceof List?null:(String)geo.getNumber());
    		pa.setLevel(geo.getLevel());
    		pa.setProvince(geo.getProvince());
    		pa.setStreet(geo.getStreet()==null || geo.getStreet() instanceof List?null:(String)geo.getStreet());
    		
    		String location = geo.getLocation();
    		pa.setLng(Double.valueOf(location.split(",")[0]));
    		pa.setLat(Double.valueOf(location.split(",")[1]));
    	}
    }
    
    @GetMapping("detail")
    public String detail(Long id,Model model){
       PitchAddr pitchAddr = pitchAddrService.getById(id);
        model.addAttribute("pitchAddr",pitchAddr);
        return "/admin/pitch-addr/detail";
    }

    @GetMapping("edit")
    public String edit(Long id,Model model){
        PitchAddr pitchAddr = pitchAddrService.getById(id);
        model.addAttribute("pitchAddr",pitchAddr);
        return "/admin/pitch-addr/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    public RestResponse edit(PitchAddr pitchAddr){
        if(null == pitchAddr.getId() || 0 == pitchAddr.getId()){
            return RestResponse.failure("ID不能为空");
        }
        if(StringUtils.isEmpty(pitchAddr.getPitchAddress())) {
   		 return RestResponse.failure("地址必须输入");
   	}
        
        PitchAddr pa = pitchAddrService.getById(pitchAddr.getId());
        if(pa!=null && (!pitchAddr.getPitchAddress().equals(pa.getPitchAddress()) || pa.getLat()==null || pa.getLng()==null)) {
        	//修改了地址，需要重新填充地理编码结果信息 
        	GeocodeResp resp = GeocodeApi.getGeocode(amapKey, pitchAddr.getPitchAddress());
        	convert(resp, pa);
        } 
        
        pa.setChannelArea(pitchAddr.getChannelArea());
        pa.setPitchAddress(pitchAddr.getPitchAddress());
        pa.setPitchAddressIntro(pitchAddr.getPitchAddressIntro());
        pa.setScopeBusiness(pitchAddr.getScopeBusiness());
        pa.setIsGovPublish(pitchAddr.getIsGovPublish());
        
        pitchAddrService.updateById(pa);
        return RestResponse.success();
    }
    
    @PostMapping("batchDel")
    @ResponseBody
    public RestResponse batchDel(@RequestParam(value = "ids[]",required = false)List<Long> ids){
        if(null == ids || ids.size()==0){
            return RestResponse.failure("请选择一项");
        }
        return RestResponse.success().setDataOnlyResult( pitchAddrService.removeByIds(ids));
    }

    @PostMapping("delete")
    @ResponseBody
    public RestResponse delete(@RequestParam(value = "id",required = false)Long id){
        if(null == id || 0 == id){
            return RestResponse.failure("ID不能为空");
        }
        return RestResponse.success().setDataOnlyResult(pitchAddrService.removeById(id));
    }
    
    @PostMapping("change-status")
    @ResponseBody
    public RestResponse change_status(@RequestParam(value = "id",required = true)Long id,@RequestParam(value = "status",required = false)Boolean status){
       PitchAddr pitchAddr = pitchAddrService.getById(id);
        pitchAddr.setDelFlag(status);
        pitchAddrService.updateById(pitchAddr);
        return RestResponse.success();
    }

}